<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>聊天界面</title>
		<link href="../css/chat.css" rel="stylesheet" />
		<script src="../js/mui.min.js"></script>
		<link href="../css/mui.min.css" rel="stylesheet" />
	</head>
	<body>
		<div class="header mui-bar mui-bar-nav">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
			<img src="https://profile-avatar.csdnimg.cn/default.jpg!1" alt="头像" />
			<h1 class="mui-title">聊天标题</h1>
		</div>

		<div class="chat-container">
			<div class="chat-box" id="chat-box"></div>

			<div class="input-area">
				<input type="text" id="message-input" placeholder="请输入消息..." />
				<button id="send-btn">发送</button>
			</div>
		</div>

		<script>
			// 缓存头像路径
			const userAvatar = "https://profile-avatar.csdnimg.cn/default.jpg!1"; // 用户头像路径
			const otherAvatar = "https://profile-avatar.csdnimg.cn/default.jpg!1"; // 其他用户头像路径

			// 加载聊天记录
			function loadChatMessages() {
				const userID = localStorage.getItem('chatID');
				fetch('http://tcp.gykang.eu.org:8080/api/chat/get?id='+userID)
					.then(response => response.json())
					.then(messages => {
						const chatBox = document.getElementById('chat-box');
						chatBox.innerHTML = ''; // 清空当前聊天框

						messages.forEach(message => {
							for (let key in message) {
								const isUserMessage = key === 'me';
								const messageElement = document.createElement('div');
								messageElement.classList.add('chat-message');

								if (isUserMessage) {
									messageElement.classList.add('user');
									messageElement.innerHTML = `<div class="message-content">${message[key]}</div>`;
								} else {
									messageElement.innerHTML = `
                  <div class="avatar">
                    <img src="${otherAvatar}" alt="对方头像" />
                    <div class="username">${key}</div>
                  </div>
                  <div class="message-content">${message[key]}</div>
                `;
								}

								chatBox.appendChild(messageElement);
							}
						});

						chatBox.scrollTop = chatBox.scrollHeight;
					})
					.catch(error => console.error('获取聊天数据失败:', error));
			}

			// 上传消息到服务器
			function uploadMessage(message) {
				const uid = localStorage.getItem('loginID'); // 用户Name
				const touid = localStorage.getItem('chatID');
				const url = `http://tcp.gykang.eu.org:8080/api/chat/upload`;

				fetch(url, {
						method: 'POST',
						headers: {
							'Content-Type': 'application/json'
						},
						body: JSON.stringify({
							msg: message,
							from: uid,
							to:touid
						}) // 如果服务器需要JSON格式，可以添加body
					})
					.then(response => response.json())
					.then(data => {
						console.log("消息上传成功", data);
					})
					.catch(error => console.error("消息上传失败", error));
			}

			// 发送消息
			document.getElementById('send-btn').addEventListener('click', function() {
				const messageInput = document.getElementById('message-input');
				const messageText = messageInput.value.trim();

				if (messageText !== "") {
					const chatBox = document.getElementById('chat-box');

					// 显示用户消息
					const userMessage = document.createElement('div');
					userMessage.classList.add('chat-message', 'user');
					userMessage.innerHTML = `<div class="message-content">${messageText}</div>`;

					chatBox.appendChild(userMessage);
					chatBox.scrollTop = chatBox.scrollHeight;

					// 清空输入框
					messageInput.value = "";

					// 上传消息
					uploadMessage(messageText);
				}
			});

			// 按回车键发送消息
			document.getElementById('message-input').addEventListener('keydown', function(event) {
				if (event.key === 'Enter') {
					document.getElementById('send-btn').click();
				}
			});

			// 每秒更新聊天记录
			setInterval(loadChatMessages, 1000);

			// 页面加载时获取聊天记录
			window.onload = function() {
				const userID = localStorage.getItem('chatID');
				console.log('用户ID:', userID);
				loadChatMessages();
			};
		</script>
	</body>
</html>